package com.tongcao.cn.nacos;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;

import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * @author:tongcao
 * @since:2019/7/25 10:38
 * Description:
 */
public class NacosExample {


    public static void main(String[] args) throws NacosException, InterruptedException {
        String serverAddr = "10.1.24.23:8848";
        String dataId = "nacos.cfg.dataId";
        String group = "test";
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
        ConfigService configService = NacosFactory.createConfigService(properties);
        String content = configService.getConfig(dataId, group, 5000);
        System.out.println(content);
        configService.addListener(dataId, group, new Listener() {
            @Override
            public void receiveConfigInfo(String configInfo) {
                System.out.println("recieve:" + configInfo);
                System.out.println(configService.getServerStatus());
            }

            @Override
            public Executor getExecutor() {
                return Executors.newSingleThreadExecutor();
            }
        });

//        发布配置
        boolean isPublishOk = configService.publishConfig(dataId, group, "content");
        System.out.println("isPublishOk = " + isPublishOk);

        Thread.sleep(3000);
        content = configService.getConfig(dataId, group, 5000);
        System.out.println("content = " + content);

//        删除配置
        boolean isRemoveOk = configService.removeConfig(dataId, group);
        System.out.println("isRemoveOk = " + isRemoveOk);
        Thread.sleep(3000);

        content = configService.getConfig(dataId, group, 5000);
        System.out.println("content = " + content);
        Thread.sleep(300000);
    }
}